from SKO.AbstractDPJob import AbstractDPJob
import sys, datetime, json, logging, os, time, math
import pandas as pd
import numpy as np
from numpy import array
import cvxpy as cp
from SKO.PSO import PSO
tmpl_no = '202309_01'

cog_dest = '发电'
# cog_dest = '补充COG'
# PSO的参数
w = 0.8  # 惯性因子，一般取1
c1 = 2  # 学习因子，一般取2
c2 = 2  #
# dim = 20  # 维度的维度
size = 100  # 种群大小，即种群中小鸟的个数
iter_num = 100  # 算法最大迭代次数
# max_vel = 0.5  # 限制粒子的最大速度
max_vel = 1

max_constant = 1000000
#读数据
data_meizhong = pd.read_excel('炼焦煤煤种.xlsx')
data_meizhong.columns = data_meizhong.columns.str.upper()
data_bili = pd.read_excel('炼焦煤比例限制.xlsx')
data_bili.columns = data_bili.columns.str.upper()
data_meizhi = pd.read_excel('炼焦煤煤质.xlsx')
data_meizhi.columns = data_meizhi.columns.str.upper()
data_shangxiaxian = pd.read_excel('炼焦煤煤质上下限.xlsx')
data_shangxiaxian.columns = data_shangxiaxian.columns.str.upper()
data_price = pd.read_excel('炼焦煤价格.xlsx')
data_price.columns = data_price.columns.str.upper()
#去除资源量为0的品种，减少变量
#月初库存
data_meizhong.INIT_INV.fillna(0, inplace=True)
#可供资源
data_meizhong.INV_WT.fillna(0, inplace=True)
#资源量
data_meizhong.RESOURCE_WT.fillna(0, inplace=True)
#计划使用量
data_meizhong.PLAN_WT.fillna(0, inplace=True)
def __cal_max_wt(x):
    rst = max(x.RESOURCE_WT, x.PLAN_WT)
    return rst
data_meizhong['MAX_WT'] = data_meizhong.apply(lambda x: __cal_max_wt(x), axis=1)
data_meizhong = data_meizhong[(data_meizhong['MAX_WT'] > 0)]
data_meizhong = data_meizhong.reset_index(drop=True)
# ganmeiliang = data_meizhong['PLAN_WT'].sum()
peihemei_wt = data_meizhong['PLAN_WT'].sum()

#对煤种生成唯一编码mark
#维度上只考虑VAR性状，SOURCE来源
#写死维度种类对应关系？
data_mark = data_meizhong.copy()
def __cal_rank_xingzhuang(x):
    if x.VAR == '主焦':
        rst = 1
    elif x.VAR == '肥煤':
        rst = 2
    elif x.VAR == '1/3焦':
        rst = 3
    elif x.VAR == '气煤':
        rst = 4
    elif x.VAR == '瘦煤':
        rst = 5
    else:
        rst = 6
    return rst
data_mark['xingzhuang_rank'] = data_mark.apply(lambda x: __cal_rank_xingzhuang(x), axis=1)
def __cal_rank_laiyuan(x):
    if x.SOURCE == '进口':
        rst = 1
    elif x.SOURCE == '大矿长协':
        rst = 2
    elif x.SOURCE == '大矿市场':
        rst = 3
    elif x.SOURCE == '地方矿':
        rst = 4
    else:
        rst = 5
    return rst
data_mark['laiyuan_rank'] = data_mark.apply(lambda x: __cal_rank_laiyuan(x), axis=1)
def __cal_rank_group(x):
    rst = str(x.xingzhuang_rank) + '_' + str(x.laiyuan_rank)
    return rst
data_mark['group'] = data_mark.apply(lambda x: __cal_rank_group(x), axis=1)
data_mark = data_mark.reset_index(drop=False)
data_mark.rename(columns={'index': 'index_old'}, inplace=True)

data_mark['rank0'] = data_mark['index_old'].groupby(data_mark['group']).rank()
data_mark['pinming_rank'] = data_mark['rank0'].astype(int)
def __cal_rank_mark(x):
    rst = str(x.group) + '_' + str(x.pinming_rank)
    return rst
data_mark['mark'] = data_mark.apply(lambda x: __cal_rank_mark(x), axis=1)
data_mark.drop(['rank0'], axis=1, inplace=True)
# 统计个数，做个var_df以便后续对应
var_list = ['主焦', '肥煤', '1/3焦', '气煤', '瘦煤']
source_list = ['进口', '大矿长协', '大矿市场', '地方矿']
var_df = pd.DataFrame(columns=['VAR', 'SOURCE', 'group', 'count'])
dict = {}
for i in range(1, len(var_list) + 1):
    for j in range(1, len(source_list) + 1):
        df = data_mark[
            (data_mark['VAR'] == var_list[i - 1]) & (data_mark['SOURCE'] == source_list[j - 1])]
        row_count = df.shape[0]
        # print("行数：", row_count)
        dict['VAR'] = var_list[i - 1]
        dict['SOURCE'] = source_list[j - 1]
        dict['group'] = str(i) + '_' + str(j)
        dict['count'] = row_count
        new_row = pd.Series(dict)
        var_df = var_df.append(new_row, ignore_index=True)
#生成动态参数
#资源量，分配比例上下限
#资源量，按照品名的
data_ziyuanliang_1 = data_mark[['PROD_CODE', 'INIT_INV', 'INV_WT', 'RESOURCE_WT', 'MERGE_TAG', 'MAX_WT', 'mark']]
data_ziyuanliang_1.RESOURCE_WT.fillna(0, inplace=True)
for index, row in data_ziyuanliang_1.iterrows():
    exec('ziyuanliang_{} ={}'.format(row['mark'], row['MAX_WT']))
#资源量，合并单元格的
merge_num = data_mark["MERGE_TAG"].max()
print(merge_num)
for i in range(1, int(merge_num)+1):
    print(i)
    data_ziyuanliang_2 = data_ziyuanliang_1[(data_ziyuanliang_1['MERGE_TAG'] == i)]
    data_ziyuanliang_2 = data_ziyuanliang_2.reset_index(drop=True)
    tmp_merge_ziyuanliang = data_ziyuanliang_2.loc[0]['INV_WT']
    exec('merge_ziyuanliang_{} ={}'.format(i, tmp_merge_ziyuanliang))
#分配比例上下限，按照品名的
data_bili.rename(columns={'MAX_VALUE': 'UL'}, inplace=True)
data_bili.rename(columns={'MIN_VALUE': 'LL'}, inplace=True)
data_bili.UL.fillna(100, inplace=True)
data_bili.LL.fillna(0, inplace=True)
data_bili_1 = data_bili[(data_bili['FLAG'] == '品名')]
data_bili_1 = data_bili_1.reset_index(drop=True)
data_bili_1 = data_bili_1[['PROD_CODE', 'UL', 'LL']]
v = ['PROD_CODE']
df3 = pd.merge(data_mark, data_bili_1, on=v, how='left')
for index, row in df3.iterrows():
    exec('ul_{} ={}'.format(row['mark'], row['UL']))
    exec('ll_{} ={}'.format(row['mark'], row['LL']))
#分配比例上下限，按照性状的
for i in range(0, len(var_list)):
    print(var_list[i])
    tmp_var = var_list[i]
    data_bili_2 = data_bili[(data_bili['FLAG'] == '性状') & (data_bili['VAR'] == tmp_var)]
    data_bili_2 = data_bili_2.reset_index(drop=True)
    tmp_ul = data_bili_2.loc[0]['UL']
    tmp_ll = data_bili_2.loc[0]['LL']
    exec('ul_var_{} ={}'.format(i+1, tmp_ul))
    exec('ll_var_{} ={}'.format(i+1, tmp_ll))
#分配比例上下限，按照来源的
for i in range(0, len(source_list)):
    print(source_list[i])
    tmp_source = source_list[i]
    data_bili_3 = data_bili[(data_bili['FLAG'] == '来源') & (data_bili['SOURCE'] == tmp_source)]
    data_bili_3 = data_bili_3.reset_index(drop=True)
    tmp_ul = data_bili_3.loc[0]['UL']
    tmp_ll = data_bili_3.loc[0]['LL']
    exec('ul_source_{} ={}'.format(i+1, tmp_ul))
    exec('ll_source_{} ={}'.format(i+1, tmp_ll))
#分配比例上下限，按照性状来源的

# var_df_1 = var_df[(var_df['count'] > 0)]
# var_df_1 = var_df_1.reset_index(drop=True)

var_df1 = var_df.copy()
def __cal_new_var(x):
    rst = str(x.VAR) + '_' + str(x.SOURCE)
    return rst
var_df1['NEW_VAR'] = var_df1.apply(lambda x: __cal_new_var(x), axis=1)

data_bili_4 = data_bili[(data_bili['FLAG'] == '性状来源')]
data_bili_4 = data_bili_4.reset_index(drop=True)
def __cal_new_var(x):
    rst = str(x.VAR) + '_' + str(x.SOURCE)
    return rst
data_bili_4['NEW_VAR'] = data_bili_4.apply(lambda x: __cal_new_var(x), axis=1)
data_bili_4 = data_bili_4[['NEW_VAR', 'UL', 'LL']]
v = ['NEW_VAR']
df3 = pd.merge(var_df1, data_bili_4, on=v, how='left')
for index, row in df3.iterrows():
    exec('ul_group_{} ={}'.format(row['group'], row['UL']))
    exec('ll_group_{} ={}'.format(row['group'], row['LL']))
#煤质
data_meizhi.rename(columns={'ASH': 'hui'}, inplace=True)
data_meizhi.rename(columns={'COKE_VM': 'huifa'}, inplace=True)
data_meizhi.rename(columns={'S': 'liu'}, inplace=True)
data_meizhi_1 = data_meizhi[['PROD_CODE', 'hui', 'huifa', 'liu']]
v = ['PROD_CODE']
df3 = pd.merge(data_mark, data_meizhi_1, on=v, how='left')
df3.fillna(max_constant, inplace=True)
for index, row in df3.iterrows():
    exec('hui_{} ={}'.format(row['mark'], row['hui']))
    exec('huifa_{} ={}'.format(row['mark'], row['huifa']))
    exec('liu_{} ={}'.format(row['mark'], row['liu']))
#煤质上下限
data_shangxiaxian_1 = data_shangxiaxian[
    (data_shangxiaxian['FLAG'] == '上限') & (data_shangxiaxian['BIG_VAR'] == '炼焦煤')]
data_shangxiaxian_1 = data_shangxiaxian_1.reset_index(drop=True)
data_shangxiaxian_1.fillna(max_constant, inplace=True)
lianjiao_hui_ul = data_shangxiaxian_1.loc[0]['ASH']
lianjiao_huifa_ul = data_shangxiaxian_1.loc[0]['COKE_VM']
lianjiao_liu_ul = data_shangxiaxian_1.loc[0]['S']
data_shangxiaxian_2 = data_shangxiaxian[
    (data_shangxiaxian['FLAG'] == '下限') & (data_shangxiaxian['BIG_VAR'] == '炼焦煤')]
data_shangxiaxian_2 = data_shangxiaxian_2.reset_index(drop=True)
data_shangxiaxian_2.fillna(0, inplace=True)
lianjiao_hui_ll = data_shangxiaxian_2.loc[0]['ASH']
lianjiao_huifa_ll = data_shangxiaxian_2.loc[0]['COKE_VM']
lianjiao_liu_ll = data_shangxiaxian_2.loc[0]['S']
#品种价格
data_price_1 = data_price[['PROD_CODE', 'UNIT_PRICE']]
v = ['PROD_CODE']
df3 = pd.merge(data_mark, data_price_1, on=v, how='left')
df3.fillna(max_constant, inplace=True)
for index, row in df3.iterrows():
    exec('price_{} ={}'.format(row['mark'], row['UNIT_PRICE']))
#其他配置的参数
data_canshu = pd.read_excel('炼焦参数表.xlsx')
data_canshu.columns = data_canshu.columns.str.upper()
chengjiaolv_constant = data_canshu.loc[0]['COKEYR_CONST']
cogfasheng_constant = data_canshu.loc[0]['COG_GEN_CONST']
cujiaolv = data_canshu.loc[0]['SINTER_CRSCOKE_RATIO']
yejinjiaolv = data_canshu.loc[0]['COKING_METCOKRAT']
waigoujiaofenlv = data_canshu.loc[0]['PCOKE_COKEPOWD_RATE']
cogfadian = data_canshu.loc[0]['ELECOUT']
fadianmeihao = data_canshu.loc[0]['COAL_USE']
jiaotanchanliang = data_canshu.loc[0]['COKE_OUTPUT']
price_waigoudian = data_canshu.loc[0]['POWOUTSRC_PRICE']
price_tianranqi = data_canshu.loc[0]['NG_PRICE']
price_fadianmei = data_canshu.loc[0]['THMCOAL_PRICE']
data_sourceprice = pd.read_excel('炼焦资源价格表.xlsx')
data_sourceprice.columns = data_sourceprice.columns.str.upper()
data_other1 = data_sourceprice[data_sourceprice['PROD_DSCR']=='外购焦炭']
data_other1 = data_other1.reset_index(drop=True)
price_waigoujiaotan = data_other1.loc[0]['UNIT_PRICE']
data_other2 = data_sourceprice[data_sourceprice['PROD_DSCR']=='烧结燃料']
data_other2 = data_other2.reset_index(drop=True)
price_shaojieranliao = data_other2.loc[0]['UNIT_PRICE']
data_other3 = data_sourceprice[data_sourceprice['PROD_DSCR']=='COG']
data_other3 = data_other3.reset_index(drop=True)
price_cog = data_other3.loc[0]['UNIT_PRICE']
#其他配置的参数
#价格
price_waigoujiaotan = price_waigoujiaotan
price_waigoujiaofen = price_shaojieranliao
# price_tianranqi = 2.7
# price_waigoudian = 0.72
# price_fadianmei = 807.0
# price_cog = 1.39
#一些参数
# cujiaolv = 0.115
# yejinjiaolv = 0.835
waigoujiao_yejinjiaolv = 1 - waigoujiaofenlv
waigoujiao_cujiaolv = waigoujiaofenlv
COGfadian = cogfadian
# fadianmeihao = 420
# ganmeiliang = 67
# peihemei_wt = ganmeiliang

data_jieguotongji = pd.read_excel('炼焦结果统计表.xlsx')
data_jieguotongji.columns = data_jieguotongji.columns.str.upper()
data_month = data_jieguotongji[data_jieguotongji['SCHEME_NAME']=='月预算']
data_month = data_month.reset_index(drop=True)
month_unit_price = data_month.loc[0]['UNIT_PRICE']
month_ash = data_month.loc[0]['ASH']
month_coke_vm = data_month.loc[0]['COKE_VM']
month_s = data_month.loc[0]['S']
month_chengjiaolv = data_month.loc[0]['COKING_COKEYR']
month_jiaotanchanliang = data_month.loc[0]['COKE_OUTPUT']
month_cogfasheng = data_month.loc[0]['COG_GEN']
ganmeiliang = month_jiaotanchanliang / month_chengjiaolv * 100
# #价格
# price_waigoujiaotan = 2407
# price_waigoujiaofen = 1477
# price_tianranqi = 2.7
# price_waigoudian = 0.72
# price_fadianmei = 807.0
# price_cog = 1.39
# #一些参数
# cujiaolv = 0.115
# yejinjiaolv = 0.835
# waigoujiao_yejinjiaolv = 0.8
# waigoujiao_cujiaolv = 0.2
# COGfadian = 1.9
# fadianmeihao = 420
# # ganmeiliang = 67
# peihemei_wt = ganmeiliang
#构建系数矩阵
coef_df = data_mark[['mark']]
mark_list = coef_df['mark'].to_list()
array_len = len(mark_list)
#构建所有参数对应的约束df
canshu_df = pd.DataFrame(columns=['index', 'coef_name', 'step', 'mark', 'vvar', 'source', 'group', 'meizhi','merge_tag'])
dict_canshu = {}
j_start = 0
#炼焦煤总量,暂认为干煤量
#等式约束
import numpy as np
from numpy import array
e2 = array([[1] * array_len], dtype=float)
f2 = array([peihemei_wt])
#不等式约束
#资源量
#品名资源量
for j in range(j_start, j_start + int(array_len)):
    exec('y{} = array([[0] * array_len],dtype=float)'.format(j))
    exec('y{}[0,j-j_start] = 1'.format(j))
    mark_tmp = mark_list[j]
    exec('m{} = array([ziyuanliang_{}])'.format(j, mark_tmp))
    dict_canshu['index'] = j
    dict_canshu['coef_name'] = '资源量'
    if mark_tmp[0] == '1':
        buzhou_tmp = '主焦'
    elif mark_tmp[0] == '2':
        buzhou_tmp = '肥煤'
    elif mark_tmp[0] == '3':
        buzhou_tmp = '1/3焦'
    elif mark_tmp[0] == '4':
        buzhou_tmp = '气煤'
    elif mark_tmp[0] == '5':
        buzhou_tmp = '瘦煤'
    dict_canshu['step'] = buzhou_tmp
    dict_canshu['mark'] = mark_tmp
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
j_start = j_start + int(array_len)
print(m0)
print(m0[0])
print(type(m0[0]))
print(m0.max)
print(type(m0.max))
print('finish')
#合并单元格资源量

for j in range(j_start, int(merge_num)+j_start):
    print(j)
    exec('y{} = array([[0] * array_len],dtype=float)'.format(j))
    data_mark_merge = data_mark[(data_mark['MERGE_TAG'] == j-j_start+1)]
    data_mark_merge = data_mark_merge.reset_index(drop=True)
    var_tmp = data_mark_merge.loc[0]['VAR']

    data_mark_merge['if_merge'] = 1
    yuechukucun_sum = data_mark_merge['INIT_INV'].sum()
    data_mark_merge = data_mark_merge[['mark', 'if_merge']]
    v = ['mark']
    df3_merge = pd.merge(coef_df, data_mark_merge, on=v, how='left')
    df3_merge.if_merge.fillna(0, inplace=True)
    for index, row in df3_merge.iterrows():
        exec('y{}[0,index] = row["if_merge"]'.format(j))
    exec('m{} = array([merge_ziyuanliang_{}+yuechukucun_sum])'.format(j, j-j_start+1))

    dict_canshu['index'] = j
    dict_canshu['coef_name'] = '合并可供资源量'
    dict_canshu['step'] = '合并可供资源量'
    dict_canshu['merge_tag'] = j -j_start + 1
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}

j_start = j_start + int(merge_num)
#分配比例
#性状分配比例
ldict1 = {}
ldict2 = {}
for i in range(1,len(var_list)+1):
    var_tmp = str(i)
    #上限
    coef_df1 = coef_df.copy()
    exec('true_value = 100 - ul_var_{}'.format(var_tmp), locals(), ldict1)
    true_value = ldict1["true_value"]
    # print(true_value)
    exec('false_value = - ul_var_{}'.format(var_tmp), locals(), ldict1)
    false_value = ldict1["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark[0] == var_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '性状比例上限'
    dict_canshu['step'] = '维度比例上下限'
    dict_canshu['vvar'] = var_list[i-1]
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
    #下限
    coef_df1 = coef_df.copy()
    exec('true_value = ll_var_{} - 100'.format(var_tmp), locals(), ldict2)
    true_value = ldict2["true_value"]
    # print(true_value)
    exec('false_value = ll_var_{}'.format(var_tmp), locals(), ldict2)
    false_value = ldict2["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark[0] == var_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '性状比例下限'
    dict_canshu['step'] = '维度比例上下限'
    dict_canshu['vvar'] = var_list[i - 1]
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
#来源分配比例
ldict3 = {}
ldict4 = {}
for i in range(1,len(source_list)+1):
    source_tmp = str(i)
    #上限
    coef_df1 = coef_df.copy()
    exec('true_value = 100 - ul_source_{}'.format(source_tmp), locals(), ldict3)
    true_value = ldict3["true_value"]
    # print(true_value)
    exec('false_value = - ul_source_{}'.format(source_tmp), locals(), ldict3)
    false_value = ldict3["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark[2] == source_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '来源比例上限'
    dict_canshu['step'] = '维度比例上下限'
    dict_canshu['source'] = source_list[i-1]
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
    #下限
    coef_df1 = coef_df.copy()
    exec('true_value = ll_source_{} - 100'.format(source_tmp), locals(), ldict4)
    true_value = ldict4["true_value"]
    # print(true_value)
    exec('false_value = ll_source_{}'.format(source_tmp), locals(), ldict4)
    false_value = ldict4["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark[2] == source_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '来源比例下限'
    dict_canshu['step'] = '维度比例上下限'
    dict_canshu['source'] = source_list[i-1]
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
#性状来源分配比例
group_list = var_df['group'].to_list()
ldict5 = {}
ldict6 = {}
for group_tmp in group_list:
    # 上限
    coef_df1 = coef_df.copy()
    exec('true_value = 100 - ul_group_{}'.format(group_tmp), locals(), ldict5)
    true_value = ldict5["true_value"]
    # print(true_value)
    exec('false_value = - ul_group_{}'.format(group_tmp), locals(), ldict5)
    false_value = ldict5["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark[0:3] == group_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '性状来源比例上限'
    dict_canshu['step'] = '维度比例上下限'
    if group_tmp[0] == '1':
        var_tmp = '主焦'
    elif group_tmp[0] == '2':
        var_tmp = '肥煤'
    elif group_tmp[0] == '3':
        var_tmp = '1/3焦'
    elif group_tmp[0] == '4':
        var_tmp = '气煤'
    elif group_tmp[0] == '5':
        var_tmp = '瘦煤'
    dict_canshu['vvar'] = var_tmp
    if group_tmp[2] == '1':
        source_tmp = '进口'
    elif group_tmp[2] == '2':
        source_tmp = '大矿长协'
    elif group_tmp[2] == '3':
        source_tmp = '大矿市场'
    elif group_tmp[2] == '4':
        source_tmp = '地方矿'
    dict_canshu['source'] = source_tmp
    dict_canshu['group'] = group_tmp
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
    # 下限
    coef_df1 = coef_df.copy()
    exec('true_value = ll_group_{} - 100'.format(group_tmp), locals(), ldict6)
    true_value = ldict6["true_value"]
    # print(true_value)
    exec('false_value = ll_group_{}'.format(group_tmp), locals(), ldict6)
    false_value = ldict6["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark[0:3] == group_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '性状来源比例下限'
    dict_canshu['step'] = '维度比例上下限'
    if group_tmp[0] == '1':
        var_tmp = '主焦'
    elif group_tmp[0] == '2':
        var_tmp = '肥煤'
    elif group_tmp[0] == '3':
        var_tmp = '1/3焦'
    elif group_tmp[0] == '4':
        var_tmp = '气煤'
    elif group_tmp[0] == '5':
        var_tmp = '瘦煤'
    dict_canshu['vvar'] = var_tmp
    if group_tmp[2] == '1':
        source_tmp = '进口'
    elif group_tmp[2] == '2':
        source_tmp = '大矿长协'
    elif group_tmp[2] == '3':
        source_tmp = '大矿市场'
    elif group_tmp[2] == '4':
        source_tmp = '地方矿'
    dict_canshu['source'] = source_tmp
    dict_canshu['group'] = group_tmp
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
#品名分配比例
ldict7 = {}
ldict8 = {}
for mark_tmp in mark_list:
    # 上限
    coef_df1 = coef_df.copy()
    exec('true_value = 100 - ul_{}'.format(mark_tmp), locals(), ldict7)
    true_value = ldict7["true_value"]
    # print(true_value)
    exec('false_value = - ul_{}'.format(mark_tmp), locals(), ldict7)
    false_value = ldict7["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark == mark_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '品种比例上限'
    if mark_tmp[0] == '1':
        buzhou_tmp = '主焦'
    elif mark_tmp[0] == '2':
        buzhou_tmp = '肥煤'
    elif mark_tmp[0] == '3':
        buzhou_tmp = '1/3焦'
    elif mark_tmp[0] == '4':
        buzhou_tmp = '气煤'
    elif mark_tmp[0] == '5':
        buzhou_tmp = '瘦煤'
    dict_canshu['step'] = buzhou_tmp
    dict_canshu['mark'] = mark_tmp
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
    # 下限
    coef_df1 = coef_df.copy()
    exec('true_value = ll_{} - 100'.format(mark_tmp), locals(), ldict8)
    true_value = ldict8["true_value"]
    # print(true_value)
    exec('false_value = ll_{}'.format(mark_tmp), locals(), ldict8)
    false_value = ldict8["false_value"]
    # print(false_value)
    def __cal_coef(x):
        if x.mark == mark_tmp:
            rst = true_value
        else:
            rst = false_value
        return rst
    coef_df1['coef'] = coef_df1.apply(lambda x: __cal_coef(x), axis=1)
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        exec("y{}[0, index] = row['coef']".format(j_start))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '品种比例下限'
    if mark_tmp[0] == '1':
        buzhou_tmp = '主焦'
    elif mark_tmp[0] == '2':
        buzhou_tmp = '肥煤'
    elif mark_tmp[0] == '3':
        buzhou_tmp = '1/3焦'
    elif mark_tmp[0] == '4':
        buzhou_tmp = '气煤'
    elif mark_tmp[0] == '5':
        buzhou_tmp = '瘦煤'
    dict_canshu['step'] = buzhou_tmp
    dict_canshu['mark'] = mark_tmp
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
#煤质
meizhi_list = ['hui', 'huifa', 'liu']
big_var_tmp = 'lianjiao'
for meizhi_tmp in meizhi_list:
    coef_df1 = coef_df.copy()
    # 上限
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        mark_tmp = row['mark']
        exec("y{}[0, index] = {}_{} - {}_{}_ul".format(j_start, meizhi_tmp, mark_tmp, big_var_tmp,
                                                       meizhi_tmp))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '上限'
    dict_canshu['step'] = '煤质上下限'
    dict_canshu['meizhi'] = meizhi_tmp
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1
    # 下限
    exec("y{} = array([[0]*array_len],dtype=float)".format(j_start))
    for index, row in coef_df1.iterrows():
        mark_tmp = row['mark']
        exec("y{}[0, index] = {}_{}_ll - {}_{}".format(j_start, big_var_tmp, meizhi_tmp, meizhi_tmp,
                                                       mark_tmp))
    exec("m{} =  array([0])".format(j_start))
    dict_canshu['index'] = j_start
    dict_canshu['coef_name'] = '下限'
    dict_canshu['step'] = '煤质上下限'
    dict_canshu['meizhi'] = meizhi_tmp
    new_row = pd.Series(dict_canshu)
    canshu_df = canshu_df.append(new_row, ignore_index=True)
    dict_canshu = {}
    j_start = j_start + 1

# 拼接
ldict0 = {}
y_str = 'y0'
# yyy = (y0,y0)
for j in range(1, j_start):
    y_str = y_str + ',' + 'y' + str(j)
# exec('yyy =({})'.format(y_str))
exec('yyy =({})'.format(y_str), locals(), ldict0)
yyy = ldict0["yyy"]
Y = np.concatenate(yyy, axis=0)

m_str = 'm0'
# mmm = (m0,m0)
for j in range(1, j_start):
    m_str = m_str + ',' + 'm' + str(j)
# exec('mmm =({})'.format(m_str))
exec('mmm =({})'.format(m_str), locals(), ldict0)
mmm = ldict0["mmm"]
M = np.concatenate(mmm, axis=0)
# print('finish')
#计划
data_mark_plan = data_mark[(data_mark['PLAN_WT'] > 0)]
data_mark_plan = data_mark_plan.reset_index(drop=True)
# mark_plan_list = data_mark_plan['mark'].to_list()
v = ['PROD_CODE']
df4 = pd.merge(data_mark_plan, data_meizhi_1, on=v, how='left')
df4 = pd.merge(df4, data_price_1, on=v, how='left')
# df4['UNIT_PRICE'] = 1
df4['TOTAL_PRICE'] = df4['UNIT_PRICE'] * df4['PLAN_WT']
df4['TOTAL_VV'] = df4['huifa'] * df4['PLAN_WT']
plan_peihemei_total_price = df4['TOTAL_PRICE'].sum()
plan_peihemei_unit_price = plan_peihemei_total_price / peihemei_wt
plan_peihemei_huifa = df4['TOTAL_VV'].sum() / peihemei_wt
plan_lilunchengjiaolv = 97 - plan_peihemei_huifa * 5 / 6 + chengjiaolv_constant
plan_jiaotanchanliang = peihemei_wt * plan_lilunchengjiaolv / 100
plan_COGfashengliang = (9.37 * plan_peihemei_huifa + 66.7) * peihemei_wt / 24 / 30 + cogfasheng_constant
#调整
#价格
#cc价格
# cc = array([[1] * array_len], dtype=float)
cc_str = ''
ldict10 = {}
for i in range(0, len(mark_list)):
    mark_tmp = mark_list[i]
    if i == 0:
        exec("cc_str = cc_str + 'price_{}'".format(mark_tmp), locals(), ldict10)
        cc_str = ldict10["cc_str"]
    else:
        exec("cc_str = cc_str + ',' + 'price_{}'".format(mark_tmp), locals(), ldict10)
        cc_str = ldict10["cc_str"]
        # print(cc_str)
exec("cc = array([{}])".format(cc_str), locals(), ldict0)
cc = ldict0["cc"]
#挥发分
vv_str = ''
ldict9 = {}
for i in range(0, len(mark_list)):
    mark_tmp = mark_list[i]
    if i == 0:
        exec("vv_str = vv_str + 'huifa_{}'".format(mark_tmp), locals(), ldict9)
        vv_str = ldict9["vv_str"]
    else:
        exec("vv_str = vv_str + ',' + 'huifa_{}'".format(mark_tmp), locals(), ldict9)
        vv_str = ldict9["vv_str"]
        # print(vv_str)
exec("vv = array([{}])".format(vv_str), locals(), ldict0)
vv = ldict0["vv"]
#线性规划优化器无法对出现判断的目标函数进行优化？
#天然气
def cal_total_cost_fadian1(x):
    peihemei_total_price = cc @ x
    peihemei_unit_price = peihemei_total_price / peihemei_wt
    peihemei_huifa = (vv @ x) / peihemei_wt
    lilunchengjiaolv = 97 - peihemei_huifa * 5 / 6 + chengjiaolv_constant
    jiaotanchanliang = peihemei_wt * lilunchengjiaolv / 100
    COGfashengliang = (9.37 * peihemei_huifa + 66.7) * peihemei_wt / 24 / 30 + cogfasheng_constant
    delta_jiaotanchanliang = jiaotanchanliang - plan_jiaotanchanliang

    delta_culiaoliang = delta_jiaotanchanliang * cujiaolv
    delta_waigoujiao = delta_jiaotanchanliang * yejinjiaolv / waigoujiao_yejinjiaolv
    delta_cujiaocaigou = delta_waigoujiao * waigoujiao_cujiaolv - delta_culiaoliang
    delta_waigoujiao_cost = -delta_waigoujiao * price_waigoujiaotan
    delta_cujiaocaigou_cost = delta_cujiaocaigou * price_waigoujiaofen
    # delta_peihemei_cost = peihemei_total_price - plan_peihemei_total_price
    delta_peihemei_cost = (peihemei_unit_price - plan_peihemei_unit_price)* ganmeiliang
    delta_COGfashengliang = (plan_COGfashengliang - COGfashengliang) * 30 * 24
    delta_COG_fadian = delta_COGfashengliang * COGfadian
    tianranqifadian = delta_COGfashengliang / 2
    fadianmeifadian = delta_COG_fadian * fadianmeihao / 100
    waigoudian = delta_COG_fadian
    delta_COG_cost1 = tianranqifadian * price_tianranqi
    delta_COG_cost2 = fadianmeifadian * price_fadianmei / 10000
    delta_COG_cost3 = waigoudian * price_waigoudian
    total_cost1 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost1
    total_cost2 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost2
    total_cost3 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost3
    return total_cost1
def cal_total_cost_fadian2(x):
    peihemei_total_price = cc @ x
    peihemei_unit_price = peihemei_total_price / peihemei_wt

    peihemei_huifa = (vv @ x) / peihemei_wt
    lilunchengjiaolv = 97 - peihemei_huifa * 5 / 6 + chengjiaolv_constant
    jiaotanchanliang = peihemei_wt * lilunchengjiaolv / 100
    COGfashengliang = (9.37 * peihemei_huifa + 66.7) * peihemei_wt / 24 / 30 + cogfasheng_constant
    delta_jiaotanchanliang = jiaotanchanliang - plan_jiaotanchanliang

    delta_culiaoliang = delta_jiaotanchanliang * cujiaolv
    delta_waigoujiao = delta_jiaotanchanliang * yejinjiaolv / waigoujiao_yejinjiaolv
    delta_cujiaocaigou = delta_waigoujiao * waigoujiao_cujiaolv - delta_culiaoliang
    delta_waigoujiao_cost = -delta_waigoujiao * price_waigoujiaotan
    delta_cujiaocaigou_cost = delta_cujiaocaigou * price_waigoujiaofen
    # delta_peihemei_cost = peihemei_total_price - plan_peihemei_total_price
    delta_peihemei_cost = (peihemei_unit_price - plan_peihemei_unit_price) * ganmeiliang
    delta_COGfashengliang = (plan_COGfashengliang - COGfashengliang) * 30 * 24
    delta_COG_fadian = delta_COGfashengliang * COGfadian
    tianranqifadian = delta_COGfashengliang / 2
    fadianmeifadian = delta_COG_fadian * fadianmeihao / 100
    waigoudian = delta_COG_fadian
    delta_COG_cost1 = tianranqifadian * price_tianranqi
    delta_COG_cost2 = fadianmeifadian * price_fadianmei / 10000
    delta_COG_cost3 = waigoudian * price_waigoudian
    total_cost1 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost1
    total_cost2 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost2
    total_cost3 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost3
    return total_cost2
def cal_total_cost_fadian3(x):
    peihemei_total_price = cc @ x
    peihemei_unit_price = peihemei_total_price / peihemei_wt

    peihemei_huifa = (vv @ x) / peihemei_wt
    lilunchengjiaolv = 97 - peihemei_huifa * 5 / 6 + chengjiaolv_constant
    jiaotanchanliang = peihemei_wt * lilunchengjiaolv / 100
    COGfashengliang = (9.37 * peihemei_huifa + 66.7) * peihemei_wt / 24 / 30 + cogfasheng_constant
    delta_jiaotanchanliang = jiaotanchanliang - plan_jiaotanchanliang

    delta_culiaoliang = delta_jiaotanchanliang * cujiaolv
    delta_waigoujiao = delta_jiaotanchanliang * yejinjiaolv / waigoujiao_yejinjiaolv
    delta_cujiaocaigou = delta_waigoujiao * waigoujiao_cujiaolv - delta_culiaoliang
    delta_waigoujiao_cost = -delta_waigoujiao * price_waigoujiaotan
    delta_cujiaocaigou_cost = delta_cujiaocaigou * price_waigoujiaofen
    # delta_peihemei_cost = peihemei_total_price - plan_peihemei_total_price
    delta_peihemei_cost = (peihemei_unit_price - plan_peihemei_unit_price) * ganmeiliang
    delta_COGfashengliang = (plan_COGfashengliang - COGfashengliang) * 30 * 24
    delta_COG_fadian = delta_COGfashengliang * COGfadian
    tianranqifadian = delta_COGfashengliang / 2
    fadianmeifadian = delta_COG_fadian * fadianmeihao / 100
    waigoudian = delta_COG_fadian
    delta_COG_cost1 = tianranqifadian * price_tianranqi
    delta_COG_cost2 = fadianmeifadian * price_fadianmei / 10000
    delta_COG_cost3 = waigoudian * price_waigoudian
    total_cost1 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost1
    total_cost2 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost2
    total_cost3 = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost3
    return total_cost3





def cal_total_cost(x):
    peihemei_total_price = cc @ x
    peihemei_unit_price = peihemei_total_price / peihemei_wt

    peihemei_huifa = (vv @ x) / peihemei_wt
    lilunchengjiaolv = 97 - peihemei_huifa * 5 / 6 + chengjiaolv_constant
    jiaotanchanliang = peihemei_wt * lilunchengjiaolv / 100
    COGfashengliang = (9.37 * peihemei_huifa + 66.7) * peihemei_wt / 24 / 30 + cogfasheng_constant
    delta_jiaotanchanliang = jiaotanchanliang - plan_jiaotanchanliang

    delta_culiaoliang = delta_jiaotanchanliang * cujiaolv
    delta_waigoujiao = delta_jiaotanchanliang * yejinjiaolv / waigoujiao_yejinjiaolv
    delta_cujiaocaigou = delta_waigoujiao * waigoujiao_cujiaolv - delta_culiaoliang
    delta_waigoujiao_cost = -delta_waigoujiao * price_waigoujiaotan
    delta_cujiaocaigou_cost = delta_cujiaocaigou * price_waigoujiaofen
    # delta_peihemei_cost = peihemei_total_price - plan_peihemei_total_price
    delta_peihemei_cost = (peihemei_unit_price - plan_peihemei_unit_price) * ganmeiliang
    delta_COGfashengliang = (plan_COGfashengliang - COGfashengliang) * 30 * 24
    # COG_DEST焦炉煤气去向
    # 发电；补充焦炉煤气


    if cog_dest != '发电':
        delta_COG_cost = delta_COGfashengliang * price_cog
    # elif cog_dest=='发电':
    else:
        delta_COG_fadian = delta_COGfashengliang * COGfadian
        tianranqifadian = delta_COGfashengliang / 2
        fadianmeifadian = delta_COG_fadian * fadianmeihao / 100
        waigoudian = delta_COG_fadian
        # 都是delta_COGfashengliang的倍数，比较倍数取最小的
        tianranqi_coef = 0.5 * price_tianranqi
        fadianmei_coef = COGfadian * fadianmeihao / 100 * price_tianranqi /10000
        waigoudian_coef = COGfadian * price_waigoudian
        delta_COG_cost1 = tianranqifadian * price_tianranqi
        delta_COG_cost2 = fadianmeifadian * price_fadianmei / 10000
        delta_COG_cost3 = waigoudian * price_waigoudian
        if tianranqi_coef <= fadianmei_coef and tianranqi_coef <= waigoudian_coef:
            delta_COG_cost = delta_COG_cost1
        elif fadianmei_coef <= tianranqi_coef and fadianmei_coef <= waigoudian_coef:
            delta_COG_cost = delta_COG_cost2
        elif waigoudian_coef <= tianranqi_coef and waigoudian_coef <= fadianmei_coef:
            delta_COG_cost = delta_COG_cost3

    total_cost = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost
    return total_cost
e1 = Y
f1 = M
if cog_dest != '发电':
    x = cp.Variable(array_len)
    print(type(x))
    obj = cp.Minimize(cal_total_cost(x))
    cons = [e1 @ x <= f1, e2 @ x == f2, x >= 0]
    prob = cp.Problem(obj, cons)
    prob.solve(solver='GLPK_MI', verbose=True)
    print("最优初始值为:", prob.value)
    print("最优初始解为：\n", x.value)
    success = 0
    if x.value is None:
        success = 0
        message = '求不出最优方案'
    x_value_tmp = x.value
    chushi_z = cal_total_cost(abs(x_value_tmp))
#cog_dest=='发电'
else:
    x1 = cp.Variable(array_len)
    obj = cp.Minimize(cal_total_cost_fadian1(x1))
    cons = [e1 @ x1 <= f1, e2 @ x1 == f2, x1 >= 0]
    prob1 = cp.Problem(obj, cons)
    prob1.solve(solver='GLPK_MI', verbose=True)
    print("最优初始值为:", prob1.value)
    print("最优初始解为：\n", x1.value)
    success = 0
    if x1.value is None:
        success = 0
        message = '求不出最优方案'
    x2 = cp.Variable(array_len)
    obj = cp.Minimize(cal_total_cost_fadian2(x2))
    cons = [e1 @ x2 <= f1, e2 @ x2 == f2, x2 >= 0]
    prob2 = cp.Problem(obj, cons)
    prob2.solve(solver='GLPK_MI', verbose=True)
    print("最优初始值为:", prob2.value)
    print("最优初始解为：\n", x2.value)
    success = 0
    if x2.value is None:
        success = 0
        message = '求不出最优方案'
    x3 = cp.Variable(array_len)
    obj = cp.Minimize(cal_total_cost_fadian3(x3))
    cons = [e1 @ x3 <= f1, e2 @ x3 == f2, x3 >= 0]
    prob3 = cp.Problem(obj, cons)
    prob3.solve(solver='GLPK_MI', verbose=True)
    print("最优初始值为:", prob3.value)
    print("最优初始解为：\n", x3.value)
    success = 0
    if x3.value is None:
        success = 0
        message = '求不出最优方案'
    if prob1.value >= prob2.value and prob1.value >= prob3.value:
        x_value_tmp = x1.value
        chushi_z = cal_total_cost_fadian1(abs(x_value_tmp))
    elif prob2.value >= prob1.value and prob2.value >= prob3.value:
        x_value_tmp = x2.value
        chushi_z = cal_total_cost_fadian2(abs(x_value_tmp))
    elif prob3.value >= prob1.value and prob3.value >= prob2.value:
        x_value_tmp = x3.value
        chushi_z = cal_total_cost_fadian3(abs(x_value_tmp))

success = 1
for i in range(0, array_len):
    mark_tmp = mark_list[i]
    value_tmp = abs(x_value_tmp[i])
    exec("chushi_x_{} = {}".format(mark_tmp, value_tmp))

###粒子初始解构造
coef_df1 = coef_df.copy()
# coef_df1['chushi'] = x.value
coef_df1['chushi'] = abs(x_value_tmp)
#存在等式约束，PSO处理等式容易出界，舍掉一个变量用其他变量去表示出来
coef_df1 = coef_df1.reset_index(drop=True)
chushi_sum = coef_df1['chushi'].sum()
print(chushi_sum)
print(ganmeiliang)


first_mark = coef_df1.loc[0]['mark']
pso_coef_df1 = coef_df1[(coef_df1['mark'] != first_mark)]
pso_coef_df1 = pso_coef_df1.reset_index(drop=True)

pso_mark_list = pso_coef_df1['mark'].to_list()
len_pso_mark = len(pso_mark_list)

dim = len_pso_mark


def build_chushi(chushi_n, chushi_value_tmp):
    for i in range(0, array_len):
        mark_tmp = mark_list[i]
        coef_df2 = coef_df1[coef_df1['mark'] == mark_tmp]
        coef_df2 = coef_df2.reset_index(drop=True)
        chushi_value = coef_df2.loc[0]['chushi']
        if int(chushi_value_tmp) != int(chushi_value):
            chushi_value_tmp = chushi_value_tmp
            # chushi_value_tmp = int(chushi_value_tmp) + diff
            e24 = array([[0] * array_len], dtype=float)
            e24[0, i] = 1
            e22 = (e2, e24)
            e222 = np.concatenate(e22, axis=0)
            f222 = array([peihemei_wt, chushi_value_tmp])
            x = cp.Variable(array_len)
            obj = cp.Minimize(cal_total_cost(x))
            cons = [e1 @ x <= f1, e222 @ x == f222, x >= 0]
            prob = cp.Problem(obj, cons)
            prob.solve(solver='GLPK_MI', verbose=True)
            success = 0
            if x.value is None:
                success = 0
            else:
                success = 1
                chushi_n = chushi_n + 1
                coef_df1[str(chushi_n)] = abs(x.value)
    return chushi_n


def build_chushi2(chushi_n, diff):
    for i in range(0, array_len):
        mark_tmp = mark_list[i]
        coef_df2 = coef_df1[coef_df1['mark'] == mark_tmp]
        coef_df2 = coef_df2.reset_index(drop=True)
        chushi_value_tmp = coef_df2.loc[0]['chushi']
        chushi_value_tmp = int(chushi_value_tmp) + diff
        if chushi_value_tmp >= 0:
            e24 = array([[0] * array_len], dtype=float)
            e24[0, i] = 1
            e22 = (e2, e24)
            e222 = np.concatenate(e22, axis=0)
            f222 = array([peihemei_wt, chushi_value_tmp])
            x = cp.Variable(array_len)
            obj = cp.Minimize(cal_total_cost(x))
            cons = [e1 @ x <= f1, e222 @ x == f222, x >= 0]
            prob = cp.Problem(obj, cons)
            prob.solve(solver='GLPK_MI', verbose=True)
            success = 0
            if x.value is None:
                success = 0
            else:
                success = 1
                chushi_n = chushi_n + 1
                coef_df1[str(chushi_n)] = abs(x.value)
    return chushi_n


chushi_n = 0
# 置0初始解
# for i in range(0, 20):
#     chushi_value_tmp = i
#     chushi_n = build_chushi(chushi_n, chushi_value_tmp)
for i in range(1, 20):
    chushi_n = build_chushi2(chushi_n, i*0.1)
    chushi_n = build_chushi2(chushi_n, -i*0.1)
    if chushi_n >= 3 * size:
        break
max_contant2 = peihemei_wt
low = [0] * len_pso_mark
up = [max_constant] * len_pso_mark
for i in range(0, len_pso_mark):
    pso_mark_tmp = pso_mark_list[i]
    exec('up[i] = min(max_constant,ziyuanliang_{})'.format(pso_mark_tmp))
# print(up)
bound = []  # 变量的约束范围
bound.append(low)
bound.append(up)
coef_df1_1 = coef_df1[coef_df1['mark'] != first_mark]
coef_df1_1 = coef_df1_1.reset_index(drop=True)
coef_df1_1.drop(['mark'], axis=1, inplace=True)
coef_df1_1.drop(['chushi'], axis=1, inplace=True)

X_df = coef_df1_1.T
X_df_sample = X_df.sample(n=size)
X_df_sample = X_df_sample.reset_index(drop=True)

XNd = X_df_sample.values
# 初始化种群的各个粒子的速度
V = np.random.uniform(-max_vel, max_vel, size=(size, dim))
# pso_cc价格
pso_cc_str = ''
ldict11 = {}
for i in range(0, len(pso_mark_list)):
    pso_mark_tmp = pso_mark_list[i]
    if i == 0:
        exec("pso_cc_str = pso_cc_str + 'price_{}'".format(pso_mark_tmp), locals(), ldict11)
        pso_cc_str = ldict11["pso_cc_str"]
    else:
        exec("pso_cc_str = pso_cc_str + ',' + 'price_{}'".format(pso_mark_tmp), locals(), ldict11)
        pso_cc_str = ldict11["pso_cc_str"]
        # print(cc_str)
exec("pso_cc = array([{}])".format(pso_cc_str), locals(), ldict0)
pso_cc = ldict0["pso_cc"]
# print(type(XNd[0]))
# print(XNd[0])
# print(XNd[0].shape)
# tmp_x = XNd[0]
# print(tmp_x.shape)
# sum_all_tmp = np.sum(tmp_x)
# print(sum_all_tmp)
# first_mark_wt_tmp = abs(peihemei_wt - sum_all_tmp)
# tmp_x_new = np.insert(tmp_x,0,first_mark_wt_tmp,axis=0)
# print(tmp_x_new.shape)
#
# tmp_x_new_T = tmp_x_new.T
# print(tmp_x_new_T.shape)
# TMP_z = cal_total_cost(abs(tmp_x_new_T))
# TMP_z2 = cal_total_cost(abs(tmp_x_new))
# print('finish')
def calc_f(X):
    x_tmp = X
    sum_x_tmp = np.sum(x_tmp)
    first_mark_wt_tmp = abs(peihemei_wt - sum_x_tmp)
    new_x_tmp = np.insert(x_tmp, 0, first_mark_wt_tmp, axis=0)
    # z_tmp = cal_total_cost(abs(new_x_tmp))
    x = abs(new_x_tmp)
    peihemei_total_price = cc @ x
    peihemei_unit_price = peihemei_total_price / peihemei_wt

    peihemei_huifa = (vv @ x) / peihemei_wt
    lilunchengjiaolv = 97 - peihemei_huifa * 5 / 6 + chengjiaolv_constant
    jiaotanchanliang = peihemei_wt * lilunchengjiaolv / 100
    COGfashengliang = (9.37 * peihemei_huifa + 66.7) * peihemei_wt / 24 / 30 + cogfasheng_constant
    delta_jiaotanchanliang = jiaotanchanliang - plan_jiaotanchanliang

    delta_culiaoliang = delta_jiaotanchanliang * cujiaolv
    delta_waigoujiao = delta_jiaotanchanliang * yejinjiaolv / waigoujiao_yejinjiaolv
    delta_cujiaocaigou = delta_waigoujiao * waigoujiao_cujiaolv - delta_culiaoliang
    delta_waigoujiao_cost = -delta_waigoujiao * price_waigoujiaotan
    delta_cujiaocaigou_cost = delta_cujiaocaigou * price_waigoujiaofen
    # delta_peihemei_cost = peihemei_total_price - plan_peihemei_total_price
    delta_peihemei_cost = (peihemei_unit_price - plan_peihemei_unit_price)* ganmeiliang

    delta_COGfashengliang = (plan_COGfashengliang - COGfashengliang) * 30 * 24
    # COG_DEST焦炉煤气去向
    # 发电；补充焦炉煤气

    if cog_dest != '发电':
        delta_COG_cost = delta_COGfashengliang * price_cog
    # elif cog_dest=='发电':
    else:
        delta_COG_fadian = delta_COGfashengliang * COGfadian
        tianranqifadian = delta_COGfashengliang / 2
        fadianmeifadian = delta_COG_fadian * fadianmeihao / 100
        waigoudian = delta_COG_fadian
        # 都是delta_COGfashengliang的倍数，比较倍数取最小的
        tianranqi_coef = 0.5 * price_tianranqi
        fadianmei_coef = COGfadian * fadianmeihao / 100 * price_tianranqi /10000
        waigoudian_coef = COGfadian * price_waigoudian
        delta_COG_cost1 = tianranqifadian * price_tianranqi
        delta_COG_cost2 = fadianmeifadian * price_fadianmei / 10000
        delta_COG_cost3 = waigoudian * price_waigoudian
        if delta_COGfashengliang >= 0:
            if tianranqi_coef <= fadianmei_coef and tianranqi_coef <= waigoudian_coef:
                delta_COG_cost = delta_COG_cost1
            elif fadianmei_coef <= tianranqi_coef and fadianmei_coef <= waigoudian_coef:
                delta_COG_cost = delta_COG_cost2
            elif waigoudian_coef <= tianranqi_coef and waigoudian_coef <= fadianmei_coef:
                delta_COG_cost = delta_COG_cost3
        else:
            if tianranqi_coef >= fadianmei_coef and tianranqi_coef >= waigoudian_coef:
                delta_COG_cost = delta_COG_cost1
            elif fadianmei_coef >= tianranqi_coef and fadianmei_coef >= waigoudian_coef:
                delta_COG_cost = delta_COG_cost2
            elif waigoudian_coef >= tianranqi_coef and waigoudian_coef >= fadianmei_coef:
                delta_COG_cost = delta_COG_cost3

    total_cost = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost

    z_tmp = total_cost
    return z_tmp

Z = calc_f(XNd[0])

pso_coef_df2 = pso_coef_df1.copy()
cf_str = 'peihemei_wt -  (0'
for index, row in pso_coef_df2.iterrows():

    cf_str = cf_str + '+ x[' + str(index) + ']'
cf_str = cf_str + ')'
str1 = cf_str
# 构建mark以及对应字符串
mark_str_df = coef_df.copy()
pso_mark_df = pso_coef_df1.copy()
pso_mark_df.drop(['chushi'], axis=1, inplace=True)
pso_mark_df = pso_mark_df.reset_index(drop=True)
pso_mark_df = pso_mark_df.reset_index(drop=False)
pso_mark_df.rename(columns={'index': 'rank'}, inplace=True)
pso_mark_df['rank0'] = pso_mark_df['rank'].astype(int)
pso_mark_df.drop(['rank'], axis=1, inplace=True)


def __cal_coef(x):
    rst = 'x[' + str(x.rank0) + ']'
    return rst


pso_mark_df['pso_str'] = pso_mark_df.apply(lambda x: __cal_coef(x), axis=1)
pso_mark_df['pso'] = 1
v = ['mark']
mark_str_df = pd.merge(mark_str_df, pso_mark_df, on=v, how='left')


def __cal_str(x):
    if x.mark == first_mark:
        rst = '(' + str1 + ')'
    else:
        rst = x.pso_str
    return rst
mark_str_df['pso_str_final'] = mark_str_df.apply(lambda x: __cal_str(x), axis=1)
for j in range(0, j_start):
    mark_str_df1 = mark_str_df.copy()
    exec("mark_str_df1['coef'] = y{}.T".format(j))
    exec("mark_str_df1['m'] = m{}[0]".format(j))

    cf_str = 'lambda x: '
    for index, row in mark_str_df1.iterrows():
        cf_str = cf_str + '+' + str(row['coef']) + '*' + str(row['pso_str_final']) + '-' + str(row['m'])
    # print(j)
    exec("cf{}_str = cf_str".format(j))
    # k_start = k_start + 1
constraint_ueq_str = '('
ldict12 = {}
for k in range(0, j_start):
    # exec("constraint_ueq_str = constraint_ueq_str + cf{}_str + ','".format(k))
    exec("constraint_ueq_str = constraint_ueq_str + cf{}_str + ','".format(k), locals(), ldict12)
    constraint_ueq_str = ldict12["constraint_ueq_str"]
    # print(constraint_ueq_str)
# constraint_ueq = (lambda x: -x[0],)
constraint_ueq_str = constraint_ueq_str + ')'
# exec("constraint_ueq = {}".format(constraint_ueq_str))
exec("constraint_ueq = {}".format(constraint_ueq_str), locals(), ldict0)
constraint_ueq = ldict0["constraint_ueq"]

X_chushi = pso_coef_df1['chushi']


def calc_f2(X, scheme_name):
    x_tmp = X
    sum_x_tmp = np.sum(x_tmp)
    first_mark_wt_tmp = abs(peihemei_wt - sum_x_tmp)
    s2 = pd.Series([first_mark_wt_tmp])

    sx = pd.concat([s2, x_tmp])
    x = abs(sx)
    x = x.reset_index(drop=True)
    data_mark_out = data_mark.copy()
    data_mark_out['wt'] = x

    def __cal_new_wt(x):
        if x.wt < 0.01:
            rst = 0
        else:
            rst = x.wt
        return rst

    data_mark_out['new_wt'] = data_mark_out.apply(lambda x: __cal_new_wt(x), axis=1)
    data_mark_out.new_wt.fillna(0, inplace=True)
    data_mark_out.drop(['wt'], axis=1, inplace=True)
    data_mark_out.rename(columns={'new_wt': 'WT'}, inplace=True)
    data_mark_out.drop(['index_old'], axis=1, inplace=True)
    data_mark_out.drop(['INIT_INV'], axis=1, inplace=True)
    data_mark_out.drop(['INV_WT'], axis=1, inplace=True)
    data_mark_out.drop(['RESOURCE_WT'], axis=1, inplace=True)
    data_mark_out.drop(['MERGE_TAG'], axis=1, inplace=True)
    data_mark_out.drop(['MAX_WT'], axis=1, inplace=True)
    data_mark_out.drop(['group'], axis=1, inplace=True)
    data_mark_out.drop(['xingzhuang_rank'], axis=1, inplace=True)
    data_mark_out.drop(['laiyuan_rank'], axis=1, inplace=True)
    data_mark_out.drop(['pinming_rank'], axis=1, inplace=True)
    v = ['PROD_CODE']
    data_mark_out = pd.merge(data_mark_out, data_price_1, on=v, how='left')
    data_mark_out = pd.merge(data_mark_out, data_meizhi_1, on=v, how='left')
    data_mark_out['TOTAL_PRICE'] = data_mark_out['UNIT_PRICE'] * data_mark_out['WT']
    data_mark_out['RATIO'] = data_mark_out['WT'] / peihemei_wt
    data_mark_out['TOTAL_ASH'] = data_mark_out['hui'] * data_mark_out['WT']
    data_mark_out['TOTAL_COKE_VM'] = data_mark_out['huifa'] * data_mark_out['WT']
    data_mark_out['TOTAL_S'] = data_mark_out['liu'] * data_mark_out['WT']
    data_mark_out['PLAN_TOTAL_PRICE'] = data_mark_out['UNIT_PRICE'] * data_mark_out['PLAN_WT']
    data_mark_out['PLAN_RATIO'] = data_mark_out['PLAN_WT'] / peihemei_wt
    data_mark_out['PLAN_TOTAL_ASH'] = data_mark_out['hui'] * data_mark_out['PLAN_WT']
    data_mark_out['PLAN_TOTAL_COKE_VM'] = data_mark_out['huifa'] * data_mark_out['PLAN_WT']
    data_mark_out['PLAN_TOTAL_S'] = data_mark_out['liu'] * data_mark_out['PLAN_WT']
    df_out1 = data_mark_out.copy()
    df_out1.drop(['mark'], axis=1, inplace=True)
    df_out1.drop(['TOTAL_ASH'], axis=1, inplace=True)
    df_out1.drop(['TOTAL_COKE_VM'], axis=1, inplace=True)
    df_out1.drop(['TOTAL_S'], axis=1, inplace=True)
    df_out1.drop(['PLAN_TOTAL_PRICE'], axis=1, inplace=True)
    df_out1.drop(['PLAN_RATIO'], axis=1, inplace=True)
    df_out1.drop(['PLAN_TOTAL_ASH'], axis=1, inplace=True)
    df_out1.drop(['PLAN_TOTAL_COKE_VM'], axis=1, inplace=True)
    df_out1.drop(['PLAN_TOTAL_S'], axis=1, inplace=True)
    df_out1['FLAG'] = '明细'
    df_out1.rename(columns={'hui': 'ASH'}, inplace=True)
    df_out1.rename(columns={'huifa': 'COKE_VM'}, inplace=True)
    df_out1.rename(columns={'liu': 'S'}, inplace=True)



    def cal_tongji(df_out1,tongji_df_tmp,flag_name,varsource):
        var1_df1 = tongji_df_tmp

        var1_sum_wt = var1_df1['WT'].sum()
        var1_sum_ratio = var1_df1['RATIO'].sum()
        var1_sum_price = var1_df1['TOTAL_PRICE'].sum()
        var1_sum_hui = var1_df1['TOTAL_ASH'].sum()
        var1_sum_huifa = var1_df1['TOTAL_COKE_VM'].sum()
        var1_sum_liu = var1_df1['TOTAL_S'].sum()
        plan_var1_sum_wt = var1_df1['PLAN_WT'].sum()
        plan_var1_sum_ratio = var1_df1['PLAN_RATIO'].sum()
        plan_var1_sum_price = var1_df1['PLAN_TOTAL_PRICE'].sum()
        plan_var1_sum_hui = var1_df1['PLAN_TOTAL_ASH'].sum()
        plan_var1_sum_huifa = var1_df1['PLAN_TOTAL_COKE_VM'].sum()
        plan_var1_sum_liu = var1_df1['PLAN_TOTAL_S'].sum()
        dict = {}
        # if flag_name != '统计配合煤':
        #     dict['FLAG'] = flag_name + '模型'
        # else:
        #     dict['FLAG'] = flag_name + '模型'
        dict['FLAG'] = flag_name + '模型'
        if flag_name == '统计性状':
            dict['VAR'] = varsource
        elif flag_name == '统计来源':
            dict['SOURCE'] = varsource
        dict['WT'] = var1_sum_wt
        dict['RATIO'] = var1_sum_ratio
        dict['TOTAL_PRICE'] = var1_sum_price
        if var1_sum_wt == 0:
            dict['UNIT_PRICE'] = None
        else:
            dict['UNIT_PRICE'] = var1_sum_price / var1_sum_wt
        if var1_sum_wt == 0:
            dict['ASH'] = None
        else:
            dict['ASH'] = var1_sum_hui / var1_sum_wt
        if var1_sum_wt == 0:
            dict['COKE_VM'] = None
        else:
            dict['COKE_VM'] = var1_sum_huifa / var1_sum_wt
        if var1_sum_wt == 0:
            dict['S'] = None
        else:
            dict['S'] = var1_sum_liu / var1_sum_wt
        new_row = pd.Series(dict)
        df_out1 = df_out1.append(new_row, ignore_index=True)
        dict = {}
        # if flag_name != '统计配合煤':
        #     dict['FLAG'] = flag_name + '预算'
        # else:
        #     dict['FLAG'] = flag_name + '预算'
        dict['FLAG'] = flag_name + '预算'
        if flag_name == '统计性状':
            dict['VAR'] = varsource
        elif flag_name == '统计来源':
            dict['SOURCE'] = varsource
        dict['WT'] = plan_var1_sum_wt
        dict['RATIO'] = plan_var1_sum_ratio
        dict['TOTAL_PRICE'] = plan_var1_sum_price
        if plan_var1_sum_wt == 0:
            dict['UNIT_PRICE'] = None
        else:
            dict['UNIT_PRICE'] = plan_var1_sum_price / plan_var1_sum_wt
        if plan_var1_sum_wt == 0:
            dict['ASH'] = None
        else:
            dict['ASH'] = plan_var1_sum_hui / plan_var1_sum_wt
        if plan_var1_sum_wt == 0:
            dict['COKE_VM'] = None
        else:
            dict['COKE_VM'] = plan_var1_sum_huifa / plan_var1_sum_wt
        if plan_var1_sum_wt == 0:
            dict['S'] = None
        else:
            dict['S'] = plan_var1_sum_liu / plan_var1_sum_wt
        new_row = pd.Series(dict)
        df_out1 = df_out1.append(new_row, ignore_index=True)
        return df_out1

    tongji_df_tmp = data_mark_out[(data_mark_out['VAR'] == '主焦')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计性状','主焦')
    tongji_df_tmp = data_mark_out[(data_mark_out['VAR'] == '肥煤')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计性状','肥煤')
    tongji_df_tmp = data_mark_out[(data_mark_out['VAR'] == '1/3焦')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计性状','1/3焦')
    tongji_df_tmp = data_mark_out[(data_mark_out['VAR'] == '气煤')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计性状','气煤')
    tongji_df_tmp = data_mark_out[(data_mark_out['VAR'] == '瘦煤')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计性状','瘦煤')
    tongji_df_tmp = data_mark_out[(data_mark_out['SOURCE'] == '进口')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计来源','进口')
    tongji_df_tmp = data_mark_out[(data_mark_out['SOURCE'] == '大矿长协')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计来源','大矿长协')
    tongji_df_tmp = data_mark_out[(data_mark_out['SOURCE'] == '大矿市场')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计来源','大矿市场')
    tongji_df_tmp = data_mark_out[(data_mark_out['SOURCE'] == '地方矿')]
    df_out1 = cal_tongji(df_out1,tongji_df_tmp,'统计来源','地方矿')
    tongji_df_tmp = data_mark_out
    df_out1 = cal_tongji(df_out1,tongji_df_tmp, '统计配合煤', '')

    peihemei_total_price = cc @ x
    peihemei_unit_price = peihemei_total_price / peihemei_wt

    peihemei_huifa = (vv @ x) / peihemei_wt
    lilunchengjiaolv = 97 - peihemei_huifa * 5 / 6 +chengjiaolv_constant
    jiaotanchanliang = peihemei_wt * lilunchengjiaolv / 100
    COGfashengliang = (9.37 * peihemei_huifa + 66.7) * peihemei_wt / 24 / 30 + cogfasheng_constant
    delta_jiaotanchanliang = jiaotanchanliang - plan_jiaotanchanliang

    delta_culiaoliang = delta_jiaotanchanliang * cujiaolv
    delta_waigoujiao = delta_jiaotanchanliang * yejinjiaolv / waigoujiao_yejinjiaolv
    delta_cujiaocaigou = delta_waigoujiao * waigoujiao_cujiaolv - delta_culiaoliang
    delta_waigoujiao_cost = -delta_waigoujiao * price_waigoujiaotan
    delta_cujiaocaigou_cost = delta_cujiaocaigou * price_waigoujiaofen
    # delta_peihemei_cost = peihemei_total_price - plan_peihemei_total_price
    delta_peihemei_cost = (peihemei_unit_price - plan_peihemei_unit_price)* ganmeiliang

    delta_COGfashengliang = (plan_COGfashengliang - COGfashengliang) * 30 * 24
    # COG_DEST焦炉煤气去向
    # 发电；补充焦炉煤气

    if cog_dest != '发电':
        delta_COG_cost = delta_COGfashengliang * price_cog
    # elif cog_dest=='发电':
    else:
        delta_COG_fadian = delta_COGfashengliang * COGfadian
        tianranqifadian = delta_COGfashengliang / 2
        fadianmeifadian = delta_COG_fadian * fadianmeihao / 100
        waigoudian = delta_COG_fadian
        # 都是delta_COGfashengliang的倍数，比较倍数取最小的
        tianranqi_coef = 0.5 * price_tianranqi
        fadianmei_coef = COGfadian * fadianmeihao / 100 * price_tianranqi / 10000
        waigoudian_coef = COGfadian * price_waigoudian
        delta_COG_cost1 = tianranqifadian * price_tianranqi
        delta_COG_cost2 = fadianmeifadian * price_fadianmei / 10000
        delta_COG_cost3 = waigoudian * price_waigoudian
        if delta_COGfashengliang >= 0:
            if tianranqi_coef <= fadianmei_coef and tianranqi_coef <= waigoudian_coef:
                delta_COG_cost = delta_COG_cost1
            elif fadianmei_coef <= tianranqi_coef and fadianmei_coef <= waigoudian_coef:
                delta_COG_cost = delta_COG_cost2
            elif waigoudian_coef <= tianranqi_coef and waigoudian_coef <= fadianmei_coef:
                delta_COG_cost = delta_COG_cost3
        else:
            if tianranqi_coef >= fadianmei_coef and tianranqi_coef >= waigoudian_coef:
                delta_COG_cost = delta_COG_cost1
            elif fadianmei_coef >= tianranqi_coef and fadianmei_coef >= waigoudian_coef:
                delta_COG_cost = delta_COG_cost2
            elif waigoudian_coef >= tianranqi_coef and waigoudian_coef >= fadianmei_coef:
                delta_COG_cost = delta_COG_cost3
    total_cost = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + delta_COG_cost

    df_out2 = pd.DataFrame(columns=['数据类型', '配合煤单价', '配合煤挥发分', '理论成焦率', '焦炭产量', '煤气发生量',
                                    '焦炭产量增加','粗焦量增加' ,'配合煤重量','COG发生量减少',
                                    '外购焦减少','粗焦增加采购量','配煤单价增加','COG去向',
                                    '减少外购焦成本','增加粗焦采购成本','配煤成本增加','COG发生量变化造成的成本影响',
                                    '炼铁成本影响','总成本影响'])

    df_out1_tmp = df_out1[df_out1['FLAG']=='统计配合煤预算']
    df_out1_tmp = df_out1_tmp.reset_index(drop=True)
    plan_unit_price_tmp = df_out1_tmp.loc[0]['UNIT_PRICE']
    plan_coke_vm_tmp = df_out1_tmp.loc[0]['COKE_VM']

    dict = {}
    dict['数据类型'] = '预算方案'
    dict['配合煤单价'] = plan_unit_price_tmp
    dict['配合煤挥发分'] = plan_coke_vm_tmp
    dict['理论成焦率'] = plan_lilunchengjiaolv
    dict['焦炭产量'] = plan_jiaotanchanliang
    dict['煤气发生量'] = plan_COGfashengliang
    new_row = pd.Series(dict)
    df_out2 = df_out2.append(new_row, ignore_index=True)
    df_out1_tmp = df_out1[df_out1['FLAG'] == '统计配合煤模型']
    df_out1_tmp = df_out1_tmp.reset_index(drop=True)
    unit_price_tmp = df_out1_tmp.loc[0]['UNIT_PRICE']
    coke_vm_tmp = df_out1_tmp.loc[0]['COKE_VM']
    dict = {}
    dict['数据类型'] = '调整方案'
    dict['配合煤单价'] = unit_price_tmp
    dict['配合煤挥发分'] = coke_vm_tmp
    dict['理论成焦率'] = lilunchengjiaolv
    dict['焦炭产量'] = jiaotanchanliang
    dict['煤气发生量'] = COGfashengliang
    new_row = pd.Series(dict)
    df_out2 = df_out2.append(new_row, ignore_index=True)
    if cog_dest != '发电':
        dict = {}
        dict['数据类型'] = '对比'
        dict['焦炭产量增加'] = delta_jiaotanchanliang
        dict['粗焦量增加'] = delta_culiaoliang
        dict['配合煤重量'] = peihemei_wt
        dict['COG发生量减少'] = delta_COGfashengliang
        dict['外购焦减少'] = delta_waigoujiao
        dict['粗焦增加采购量'] = delta_cujiaocaigou
        dict['配煤单价增加'] = unit_price_tmp - plan_unit_price_tmp
        dict['COG去向'] = cog_dest
        dict['减少外购焦成本'] = delta_waigoujiao_cost
        dict['增加粗焦采购成本'] = delta_cujiaocaigou_cost
        dict['配煤成本增加'] = delta_peihemei_cost
        dict['COG发生量变化造成的成本影响'] = delta_COG_cost
        dict['炼铁成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost
        dict['总成本影响'] = total_cost
        new_row = pd.Series(dict)
        df_out2 = df_out2.append(new_row, ignore_index=True)
    else:
        delta_COG_fadian = delta_COGfashengliang * COGfadian
        tianranqifadian = delta_COGfashengliang / 2
        fadianmeifadian = delta_COG_fadian * fadianmeihao / 100
        waigoudian = delta_COG_fadian
        dict = {}
        dict['数据类型'] = '对比'
        dict['焦炭产量增加'] = delta_jiaotanchanliang
        dict['粗焦量增加'] = delta_culiaoliang
        dict['配合煤重量'] = peihemei_wt
        dict['COG发生量减少'] = delta_COGfashengliang
        dict['外购焦减少'] = delta_waigoujiao
        dict['粗焦增加采购量'] = delta_cujiaocaigou
        dict['配煤单价增加'] = unit_price_tmp - plan_unit_price_tmp
        dict['COG去向'] = '发电最优'
        dict['减少外购焦成本'] = delta_waigoujiao_cost
        dict['增加粗焦采购成本'] = delta_cujiaocaigou_cost
        dict['配煤成本增加'] = delta_peihemei_cost
        dict['COG发生量变化造成的成本影响'] = delta_COG_cost
        dict['炼铁成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost
        dict['总成本影响'] = total_cost
        new_row = pd.Series(dict)
        df_out2 = df_out2.append(new_row, ignore_index=True)
        dict = {}
        dict['数据类型'] = '对比'
        dict['焦炭产量增加'] = delta_jiaotanchanliang
        dict['粗焦量增加'] = delta_culiaoliang
        dict['配合煤重量'] = peihemei_wt
        dict['COG发生量减少'] = delta_COGfashengliang
        dict['外购焦减少'] = delta_waigoujiao
        dict['粗焦增加采购量'] = delta_cujiaocaigou
        dict['配煤单价增加'] = unit_price_tmp - plan_unit_price_tmp
        dict['COG去向'] = '发电天然气代替'
        dict['减少外购焦成本'] = delta_waigoujiao_cost
        dict['增加粗焦采购成本'] = delta_cujiaocaigou_cost
        dict['配煤成本增加'] = delta_peihemei_cost
        dict['COG发生量变化造成的成本影响'] = tianranqifadian * price_tianranqi
        dict['炼铁成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost
        dict['总成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + tianranqifadian * price_tianranqi
        new_row = pd.Series(dict)
        df_out2 = df_out2.append(new_row, ignore_index=True)
        dict = {}
        dict['数据类型'] = '对比'
        dict['焦炭产量增加'] = delta_jiaotanchanliang
        dict['粗焦量增加'] = delta_culiaoliang
        dict['配合煤重量'] = peihemei_wt
        dict['COG发生量减少'] = delta_COGfashengliang
        dict['外购焦减少'] = delta_waigoujiao
        dict['粗焦增加采购量'] = delta_cujiaocaigou
        dict['配煤单价增加'] = unit_price_tmp - plan_unit_price_tmp
        dict['COG去向'] = '发电发电煤代替'
        dict['减少外购焦成本'] = delta_waigoujiao_cost
        dict['增加粗焦采购成本'] = delta_cujiaocaigou_cost
        dict['配煤成本增加'] = delta_peihemei_cost
        dict['COG发生量变化造成的成本影响'] = fadianmeifadian * price_fadianmei / 10000
        dict['炼铁成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost
        dict['总成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + fadianmeifadian * price_fadianmei / 10000
        new_row = pd.Series(dict)
        df_out2 = df_out2.append(new_row, ignore_index=True)
        dict = {}
        dict['数据类型'] = '对比'
        dict['焦炭产量增加'] = delta_jiaotanchanliang
        dict['粗焦量增加'] = delta_culiaoliang
        dict['配合煤重量'] = peihemei_wt
        dict['COG发生量减少'] = delta_COGfashengliang
        dict['外购焦减少'] = delta_waigoujiao
        dict['粗焦增加采购量'] = delta_cujiaocaigou
        dict['配煤单价增加'] = unit_price_tmp - plan_unit_price_tmp
        dict['COG去向'] = '发电外购电代替'
        dict['减少外购焦成本'] = delta_waigoujiao_cost
        dict['增加粗焦采购成本'] = delta_cujiaocaigou_cost
        dict['配煤成本增加'] = delta_peihemei_cost
        dict['COG发生量变化造成的成本影响'] = waigoudian * price_waigoudian
        dict['炼铁成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost
        dict['总成本影响'] = delta_peihemei_cost + delta_waigoujiao_cost + delta_cujiaocaigou_cost + waigoudian * price_waigoudian
        new_row = pd.Series(dict)
        df_out2 = df_out2.append(new_row, ignore_index=True)

    data_jieguotongji_out = pd.DataFrame(
        columns=['SCHEME_NAME', 'COKING_PCC_RATIO', 'COKING_FATCOAL_RATIO', 'COKING_GFCOAL_RATIO',
                 'COKING_GASCOAL_RATIO', 'COKING_LEANCOAL_RATIO',
                 'UNIT_PRICE', 'ASH', 'COKE_VM', 'S',
                 'COKING_COKEYR', 'COKE_OUTPUT', 'COG_GEN'])
    dict = {}
    df_out1_var1 = df_out1[(df_out1['FLAG'] == '统计性状模型') & (df_out1['VAR'] == '主焦')]
    df_out1_var1 = df_out1_var1.reset_index(drop=True)
    model_var1 = df_out1_var1.loc[0]['RATIO']
    df_out1_var2 = df_out1[(df_out1['FLAG'] == '统计性状模型') & (df_out1['VAR'] == '肥煤')]
    df_out1_var2 = df_out1_var2.reset_index(drop=True)
    model_var2 = df_out1_var2.loc[0]['RATIO']
    df_out1_var3 = df_out1[(df_out1['FLAG'] == '统计性状模型') & (df_out1['VAR'] == '1/3焦')]
    df_out1_var3 = df_out1_var3.reset_index(drop=True)
    model_var3 = df_out1_var3.loc[0]['RATIO']
    df_out1_var4 = df_out1[(df_out1['FLAG'] == '统计性状模型') & (df_out1['VAR'] == '气煤')]
    df_out1_var4 = df_out1_var4.reset_index(drop=True)
    model_var4 = df_out1_var4.loc[0]['RATIO']
    df_out1_var5 = df_out1[(df_out1['FLAG'] == '统计性状模型') & (df_out1['VAR'] == '瘦煤')]
    df_out1_var5 = df_out1_var5.reset_index(drop=True)
    model_var5 = df_out1_var5.loc[0]['RATIO']
    df_out1_peihe = df_out1[(df_out1['FLAG'] == '统计配合煤模型')]
    df_out1_peihe = df_out1_peihe.reset_index(drop=True)
    model_unit_price = df_out1_peihe.loc[0]['UNIT_PRICE']
    model_ash = df_out1_peihe.loc[0]['ASH']
    model_coke_vm = df_out1_peihe.loc[0]['COKE_VM']
    model_s = df_out1_peihe.loc[0]['S']
    model_chengjiaolv = 97 - model_coke_vm * 5 / 6 + chengjiaolv_constant
    model_jiaotanchanliang = ganmeiliang * model_chengjiaolv / 100
    model_cogfasheng = (9.37 * model_coke_vm + 66.7) * ganmeiliang / 30 / 24 + cogfasheng_constant
    dict['SCHEME_NAME'] = scheme_name
    dict['COKING_PCC_RATIO'] = model_var1
    dict['COKING_FATCOAL_RATIO'] = model_var2
    dict['COKING_GFCOAL_RATIO'] = model_var3
    dict['COKING_GASCOAL_RATIO'] = model_var4
    dict['COKING_LEANCOAL_RATIO'] = model_var5
    dict['UNIT_PRICE'] = model_unit_price
    dict['ASH'] = model_ash
    dict['COKE_VM'] = model_coke_vm
    dict['S'] = model_s
    dict['COKING_COKEYR'] = model_chengjiaolv
    dict['COKE_OUTPUT'] = model_jiaotanchanliang
    dict['COG_GEN'] = model_cogfasheng
    new_row = pd.Series(dict)
    data_jieguotongji_out = data_jieguotongji_out.append(new_row, ignore_index=True)


    df_out1_rounded = df_out1.round(3)
    df_out2_rounded = df_out2.round(3)
    writer = pd.ExcelWriter('产焦产气测算明细'+cog_dest+scheme_name+'.xlsx')
    df_out1_rounded.to_excel(writer, sheet_name='Sheet1', index=False)
    writer.save()
    writer = pd.ExcelWriter('产焦产气测算统计'+cog_dest+scheme_name+'.xlsx')
    df_out2_rounded.to_excel(writer, sheet_name='Sheet1', index=False)
    writer.save()
    return df_out1_rounded,df_out2_rounded


df_out1_rounded,df_out2_rounded = calc_f2(X=X_chushi, scheme_name='优化方案')
print('finish')



pso = PSO(func=calc_f, n_dim=dim, pop=size, max_iter=iter_num, lb=low, ub=up, w=w, c1=c1, c2=c2
          , constraint_ueq=constraint_ueq, X=XNd, V=V)
pso.record_mode = True
pso.run()
# print('经过PSO计算得到的最优解：',pso.gbest_x)
best_x = pso.gbest_x
# print('此时目标函数值为',calc_f(best_x))
pbest2 = np.concatenate([pso.pbest_x, pso.pbest_y], axis=1)

idex = np.lexsort([pbest2[:, 20]])
sorted_data = pbest2[idex, :]

best_5 = sorted_data[[0, 1, 2, 3, 4]]
best_5 = np.delete(best_5, -1, 1)
print(type(best_5[0]))
ser_x = pd.Series(best_5[0].tolist())
print(type(ser_x))
df_out1_rounded1,df_out2_rounded1 = calc_f2(X=ser_x, scheme_name='其他1')
ser_x = pd.Series(best_5[1].tolist())
print(type(ser_x))
df_out1_rounded2,df_out2_rounded2 = calc_f2(X=ser_x, scheme_name='其他2')
ser_x = pd.Series(best_5[2].tolist())
print(type(ser_x))
df_out1_rounded3,df_out2_rounded3 = calc_f2(X=ser_x, scheme_name='其他3')
ser_x = pd.Series(best_5[3].tolist())
print(type(ser_x))
df_out1_rounded4,df_out2_rounded4 = calc_f2(X=ser_x, scheme_name='其他4')
ser_x = pd.Series(best_5[4].tolist())
print(type(ser_x))
df_out1_rounded5,df_out2_rounded5 = calc_f2(X=ser_x, scheme_name='其他5')

print('finish')
